package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.LogItemAdapter;
import vn.personal.anhht.bloback12.bean.LogObject;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import vn.personal.anhht.bloback12.util.LocalizationUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class TabPickLogActivity extends Activity {

    private CallBlockDatabaseAdapter databaseAdapter;
    private ArrayList<LogObject> listLog = new ArrayList<LogObject>();
    private ListView lvLogs;
    private LogItemAdapter adapterLog;
    private ProgressDialog dialog;
    Resources rs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        LocalizationUtil.setupLanguage(getApplicationContext());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pick_contact_log);
        rs = getResources();
        initLogList();
        Log.e("LOG TAB", "LOG TAB");
    }

    /*
     * AnhHT: init listview and set on item click listener for listview
     */
    public void initLogList() {
        // lvLogs = (ListView) findViewById(R.id.list_logs);
        // queryCallIncomed();
        dialog = new ProgressDialog(this);
        databaseAdapter = new CallBlockDatabaseAdapter(getApplicationContext());
        lvLogs = (ListView) findViewById(R.id.list_logs);
        adapterLog = new LogItemAdapter(getApplicationContext(),
                android.R.layout.simple_list_item_1, listLog);

        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        lvLogs.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                final LogObject currentLog = listLog.get(position);

                alert.setTitle(rs.getString(R.string.pick_alert_title));
                alert.setMessage(rs.getString(R.string.pick_alert_message));
                alert.setPositiveButton(rs.getString(R.string.ok),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                databaseAdapter.open();
                                if (databaseAdapter.isPhoneExist(currentLog
                                        .getPhone())) {
                                    databaseAdapter.close();
                                    Toast.makeText(
                                            getApplicationContext(),
                                            rs.getString(R.string.pc_phone_exist),
                                            Toast.LENGTH_LONG).show();
                                    dialog.cancel();
                                } else {
                                    String name = currentLog.getName().trim();
                                    if ("Vô Danh".equalsIgnoreCase(name)
                                            || "No Name".equalsIgnoreCase(name)) {
                                        name = currentLog.getPhone();
                                    }
                                    String phone = "";
                                    if (currentLog.getPhone().contains("+84")) {
                                        phone = "0"
                                                + currentLog.getPhone()
                                                        .substring(3);
                                    } else {
                                        phone = currentLog.getPhone();
                                    }
                                    databaseAdapter.addBlackList(name, phone,
                                            "", "", 0, 0, 0);
                                    databaseAdapter.close();
                                    getParent().setResult(
                                            Constants.RESPONSE_PICK_LOG_OK);
                                    finish();
                                }

                                /*
                                 * databaseAdapter.open();
                                 * databaseAdapter.addBlackList(
                                 * currentLog.getName(), currentLog.getPhone(),
                                 * "", ""); databaseAdapter.close();
                                 * back(Constants.RESPONSE_PICK_LOG_OK);
                                 */
                            }
                        });
                alert.setNegativeButton(rs.getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                dialog.cancel();
                            }
                        });
                alert.show();
            }
        });

        new GetLogThread().execute();
    }

    public class GetLogThread extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            queryCallIncomed();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // super.onPostExecute(result);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            lvLogs.setAdapter(adapterLog);
        }

        @Override
        protected void onPreExecute() {
            // super.onPreExecute();
            dialog.setMessage(rs.getString(R.string.pick_dialog_load));
            dialog.show();
        }

        /*
         * AnhHT:
         */
        private void queryCallIncomed() {
            String[] strFields = { android.provider.CallLog.Calls.CACHED_NAME,
                    android.provider.CallLog.Calls.DATE,
                    android.provider.CallLog.Calls.NUMBER,
                    android.provider.CallLog.Calls.TYPE };
            String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
            Cursor mCallCursor = getContentResolver().query(
                    android.provider.CallLog.Calls.CONTENT_URI, strFields,
                    null, null, strOrder);
            if (mCallCursor.moveToFirst()) {
                String mynumber = null;
                String myname = null;
                String mytype = null;
                String mydate = null;
                do {
                    LogObject lo = new LogObject();
                    mynumber = mCallCursor.getString(mCallCursor
                            .getColumnIndex(Calls.NUMBER));
                    if (mynumber == null) {
                        lo.setPhone(rs.getString(R.string.pick_string_nophone));
                    } else {
                        lo.setPhone(mynumber);
                    }
                    myname = mCallCursor.getString(mCallCursor
                            .getColumnIndex(Calls.CACHED_NAME));
                    if (myname == null) {
                        lo.setName(rs.getString(R.string.pick_string_noname));
                    } else {
                        lo.setName(myname);
                    }
                    mydate = mCallCursor.getString(mCallCursor
                            .getColumnIndex(Calls.DATE));
                    lo.setTime(vn.personal.anhht.bloback12.util.UtilMethods
                            .changeMilisecondToDate(Long.parseLong(mydate)));
                    mytype = mCallCursor.getString(mCallCursor
                            .getColumnIndex(Calls.TYPE));
                    lo.setType(Integer.parseInt(mytype.trim()));
                    listLog.add(lo);
                } while (mCallCursor.moveToNext());

            }
            mCallCursor.close();
        }
    }
}
